package com.jeesite.modules.fl.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.modules.fl.entity.*;
import com.jeesite.modules.fl.service.*;
import com.jeesite.modules.fl.utils.Utils;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.sys.entity.Area;
import com.jeesite.modules.sys.utils.AreaUtils;

@Controller
@RequestMapping(value = "${adminPath}/fl/appointment")
public class AppointmentController extends BaseController{
	
	@Autowired
	private AppointmentService appointmentService;
	@Autowired
	private ClinicService clinicService;
	@Autowired
	private LeaguerService leaguerService;
	@Autowired
	private ActionRecordService recordService;
	@Autowired
	private DoctorService doctorService;
	@Autowired
	private EvaluateService evaluateService;
	@Autowired
	private EvaluateDetailService evaluateDetailService;
	@Autowired
	private ClinicSettingService clinicSettingService;
	@Autowired
	private SysHolidayService holidayService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public Appointment get(String id, boolean isNewRecord) {
		return appointmentService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("fl:appointment:view")
	@RequestMapping(value = {"list", ""})
	public String list(Appointment appointment, HttpServletRequest request, HttpServletResponse response, Model model) {
		model.addAttribute("appointment", appointment);
		Clinic entity = new Clinic();
		entity.setStatus("0");
		List<Clinic> clinicList = clinicService.findList(entity);
		model.addAttribute("clinicList", clinicList);
		return "modules/fl/appointmentList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("fl:appointment:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<Appointment> listData(Appointment appointment, HttpServletRequest request, HttpServletResponse response) {
		Page<Appointment> page = appointmentService.findPage(new Page<Appointment>(request, response), appointment);
		return page;
	}


	
	/**
	 * 编辑表单
	 */
	@RequiresPermissions("fl:appointment:view")
	@RequestMapping(value = "form")
	public String form(Appointment appointment, Model model) {
		if(appointment.getIsNewRecord()){
			appointment.setAppointmentStatus("1");
		}else{
			appointment.setAppointmentStatus("2");
		}		
		model.addAttribute("appointment", appointment);
		Clinic entity = new Clinic();
		entity.setStatus("0");
		List<Clinic> clinicList = clinicService.findList(entity);
		model.addAttribute("clinicList", clinicList);
		Leaguer leaguer = new Leaguer();
		leaguer.setStatus("0");
		List<Leaguer> leaguerList = leaguerService.findList(leaguer);
		model.addAttribute("leaguerList", leaguerList);
		return "modules/fl/appointmentForm";
	}
	
	/**
	 * 编辑表单
	 */
	@RequiresPermissions("fl:appointment:edit")
	@RequestMapping(value = "confirm")
	public String confirm(Appointment appointment, Model model) {
		appointment.setAppointmentStatus("3");
		appointment.setTime(new Date());
		model.addAttribute("appointment", appointment);
		Doctor doctor = new Doctor();
		doctor.setStatus("0");
		doctor.setClinics(appointment.getClinic().getId());
		doctor.setRooms(appointment.getDepartment());
		List<Doctor> doctorList = doctorService.findList(doctor);
		model.addAttribute("doctorList", doctorList);
		return "modules/fl/appointmentForm";
	}
	
	
	/**
	 * 编辑表单
	 */
	@RequiresPermissions("fl:appointment:edit")
	@RequestMapping(value = "finish")
	@ResponseBody
	public String finish(Appointment appointment, Model model) {
		appointment.setAppointmentStatus("4");
		appointmentService.save(appointment);
		return renderResult(Global.TRUE, text("保存数据成功！"));
	}
	
	@RequiresPermissions("fl:appointment:edit")
	@RequestMapping(value = "mutiFinish")
	@ResponseBody
	public String mutiFinish(String ids, Model model) {
		String[] idList = ids.split(",");
		int i = 0;
		for(String id : idList){
			if(!id.isEmpty()){
				Appointment appointment = appointmentService.get(id);
				if("3".equals(appointment.getAppointmentStatus())){
					appointment.setAppointmentStatus("4");
					appointmentService.save(appointment);
					i++;
				}
			}
		}
		return renderResult(Global.TRUE, text("共有条"+i+"记录设置预约服务完成成功！"));
	}
	
	/**
	 * 编辑表单
	 */
	@RequiresPermissions("fl:appointment:edit")
	@RequestMapping(value = "cancel")
	public String cancel(Appointment appointment, Model model) {
		appointment.setAppointmentStatus("5");
		model.addAttribute("appointment", appointment);		
		return "modules/fl/appointmentForm";
	}
	
	/**
	 * 查看表单
	 */
	@RequiresPermissions("fl:appointment:view")
	@RequestMapping(value = "view")
	public String view(Appointment appointment, Model model) {
		model.addAttribute("appointment", appointment);
		ActionRecord record = new ActionRecord();
		record.setStatus("0");
		record.setAppointment(appointment);
		List<ActionRecord> recordList = recordService.findList(record);
		model.addAttribute("recordList", recordList);
		return "modules/fl/appointmentView";
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List treeData(String excludeCode, String isShowCode)
    {
        List mapList = ListUtils.newArrayList();
        List list = AreaUtils.getAreaAllList();
        for(int i = 0; i < list.size(); i++)
        {
            Area e = (Area)list.get(i);
            if("0".equals(e.getStatus()) && (e.getAreaType().equals("1")) || e.getAreaType().equals("2")) 
            {
            	Map map = MapUtils.newHashMap();
                map.put("id", e.getId());
                map.put("pId", e.getParentCode());
                map.put("name", e.getAreaName());
                mapList.add(map);

            }
        }

        return mapList;
    }

	/**
	 * 保存数据
	 */
	@RequiresPermissions("fl:appointment:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated Appointment appointment) {
		appointmentService.save(appointment);
		return renderResult(Global.TRUE, text("保存数据成功！"));
	}
	
	@PostMapping(value = "getTimePeriod")
	@ResponseBody
	public List<String> getTimePeriod(String clinicId, String department, String date, String id) {		
		List<String> timePeriods = new ArrayList<String>();
		Clinic clinic = clinicService.get(clinicId);
		SysHoliday holiday = new SysHoliday();
		holiday.setClinics(clinicId);
		holiday.setStatus("0");
		holiday.setDate(DateUtils.parseDate(date));
		List<SysHoliday> holidays = holidayService.findList(holiday);
		if(holidays.size()>0){
			if("1".equals(holidays.get(0).getHolidayStatus())){
				return timePeriods;
			}
		}else{
			if(!Utils.isBussinenssDay(date, clinic.getBusinessHours())){
				return timePeriods;
			}
		}		
		ClinicSetting entity = new ClinicSetting();
    	entity.setClinic(clinic);
    	entity.setDepartment(department);
    	entity.setStatus("0");
    	List<ClinicSetting> settingList = clinicSettingService.findList(entity);
    	if(settingList.size()>0){
    		ClinicSetting setting = settingList.get(0);
    		Integer serviceTime = setting.getServiceTime();
    		Integer number = setting.getNumber();
    		String	startTime = setting.getAmStartTime();
    		String	endTime = setting.getAmEndTime();
    		List<String> list = Utils.getPeriods(date, startTime, endTime, serviceTime);
    		startTime = setting.getPmStartTime();
    		endTime = setting.getPmEndTime();
    		list.addAll(Utils.getPeriods(date, startTime, endTime, serviceTime));
    		for(String period:list){
    			if(appointmentService.getAppointmentCountTime(clinicId, department, date, id, period) <number){
    				timePeriods.add(period);
    			}
    		}
    	}
		return timePeriods;
	}
	
	
	/**
	 * 停用数据
	 */
	@RequiresPermissions("fl:appointment:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(Appointment appointment) {
		appointment.setStatus(Appointment.STATUS_DISABLE);
		appointmentService.updateStatus(appointment);
		return renderResult(Global.TRUE, text("停用数据成功"));
	}
	
	/**
	 * 启用数据
	 */
	@RequiresPermissions("fl:appointment:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(Appointment appointment) {
		appointment.setStatus(Appointment.STATUS_NORMAL);
		appointmentService.updateStatus(appointment);
		return renderResult(Global.TRUE, text("启用数据成功"));
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("fl:appointment:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(Appointment appointment) {
		appointmentService.delete(appointment);
		return renderResult(Global.TRUE, text("删除数据成功！"));
	}
	
	@RequestMapping(value = "importTemplate")
	public void importTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		ExcelExport ee = new ExcelExport("预约数据", Appointment.class);
		try {
			String fileName = "预约数据导入模板.xlsx";
			List<Appointment> list = new ArrayList<Appointment>();
			list.add(new Appointment());
			ee.setDataList(list).write(response, fileName);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		} finally{
			ee.close();
		}
	}
	
	@RequestMapping(value = "export", method=RequestMethod.POST)
    public void exportFile(Appointment appointment, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		ExcelExport ee = new ExcelExport("预约数据", Appointment.class);
		try {
            String fileName = "预约数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx"; 	
            List<Appointment> list = appointmentService.findList(appointment);
    		ee.setDataList(list).write(response, fileName);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出预约失败！失败信息："+e.getMessage());
		} finally{
			ee.close();
		}
    }
    
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importData(MultipartFile file, String updateSupport)
    {
        String message;
        boolean isUpdateSupport = "1".equals(updateSupport);
        try{
	        message = appointmentService.importData(file, Boolean.valueOf(isUpdateSupport));
	        return renderResult("true", (new StringBuilder()).append("posfull:").append(message).toString());
        }catch(Exception ex){
        	return renderResult("false", (new StringBuilder()).append("posfull:").append(ex.getMessage()).toString());
        }
    }

    //评价相关***************************************************************
	/**
	 * 查询评价列表
	 */
	@RequiresPermissions("fl:appointment:evaluateView")
	@RequestMapping(value = {"listEvaluate", ""})
	public String listEvaluate(Appointment appointment, HttpServletRequest request, HttpServletResponse response, Model model) {
		model.addAttribute("appointment", appointment);
		Clinic entity = new Clinic();
		entity.setStatus("0");
		List<Clinic> clinicList = clinicService.findList(entity);
		model.addAttribute("clinicList", clinicList);
		return "modules/fl/evaluateList";
	}

	/**
	 * 查看表单
	 */
	@RequiresPermissions("fl:appointment:evaluateView")
	@RequestMapping(value = "evaluateView")
	public String evaluateView(Appointment appointment, Model model) {
		model.addAttribute("appointment", appointment);
		return "modules/fl/evaluateView";
	}

	/**
	 * 查询评价列表数据
	 */
	@RequiresPermissions("fl:appointment:evaluateView")
	@RequestMapping(value = "listEvaluateData")
	@ResponseBody
	public Page<Appointment> listEvaluateData(Appointment appointment, HttpServletRequest request, HttpServletResponse response) {
		appointment.setIsEvaluate("1");
		appointment.setStatus("0");
		Page<Appointment> page = new Page<Appointment>(request, response);
		appointment.setPage(page);
		page.setList(appointmentService.getEvaluates(appointment));
		return page;
	}

	/*
	 * 得到差评数
	 * */
	@RequiresPermissions("fl:appointment:evaluateView")
	@RequestMapping(value = "lowLevelEvaluateCount")
	@ResponseBody
	public String getLowLevelEvaluateCount(){
		return appointmentService.getLowLevelEvaluateCount().toString();
	}

	/**
	 * 处理完成差评
	 */
	@RequiresPermissions("fl:appointment:evaluateEdit")
	@RequestMapping(value = "endPoorRating")
	@ResponseBody
	public String endPoorRating(Appointment appointment) {
		appointment.setIsEndPoorRating("1");
		appointmentService.endPoorRating(appointment);
		return renderResult(Global.TRUE, text("处理完成"));
	}
}
